package com.chaofan.authsso.coreweb;

import com.chaofan.authsso.core.AuthSsoCore;
import com.chaofan.authsso.core.common.Constant;
import com.chaofan.authsso.core.common.SsoRestfulMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Author: Chaofan
 * Date: 2020/6/8 15:01
 * email: chaofan2685@qq.com
 */
@RestController
@RequestMapping(value = "/api")
public class LoginController {

    @Autowired
    AuthSsoCore authSsoCore;

    @PostMapping(value = "/login")
    public SsoRestfulMessage<String> login(String username,String password){
        SsoRestfulMessage ssoRestfulMessage = new SsoRestfulMessage();
        //获取用户信息
        User user = getUserByName(username);
        //对比账号密码
        if (user == null){
            ssoRestfulMessage.setCode(Constant.REQUEST_PARAMS_NOT_VALID);
            ssoRestfulMessage.setMessage("用户名或密码错误");
        }else if (username.equals(user.getUsername()) && password.equals(user.getPassword())){
            //确认登录成功后执行该方法,传入用户相关的信息,获取回跳地址
            String redirectUri = authSsoCore.setInfoWithToken(user);
            ssoRestfulMessage.setCode(Constant.SUCCESS);
            ssoRestfulMessage.setMessage("成功");
            ssoRestfulMessage.setData(redirectUri);
        }else {
            ssoRestfulMessage.setCode(Constant.REQUEST_PARAMS_NOT_VALID);
            ssoRestfulMessage.setMessage("用户名或密码错误");
        }
        return ssoRestfulMessage;
    }

    @GetMapping(value = "/getUserInfo")
    public SsoRestfulMessage<User> getUserInfo(String token){
        SsoRestfulMessage<User> ssoRestfulMessage = new SsoRestfulMessage();
        User user = (User) authSsoCore.getInfoByToken(token);
        if (user != null){
            ssoRestfulMessage.setCode(Constant.SUCCESS);
            ssoRestfulMessage.setMessage("成功");
            ssoRestfulMessage.setData(user);
        }else {
            ssoRestfulMessage.setCode(Constant.INTERNAL_SERVER_ERROR);
            ssoRestfulMessage.setMessage("用户信息获取失败");
        }
        return ssoRestfulMessage;
    }

    /**
     * 模拟从数据库中查用户数据
     * @param username
     * @return
     */
    private User getUserByName(String username){
        switch (username){
            case "admin":
                return new User("小明","admin","123456");
            case "superAdmin":
                return new User("小王","superAdmin","123456");
            default:
                return null;
        }
    }



}
